package com.mogujie.tt.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.RegisterConstant;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.ui.base.TTBaseFragment;
import com.mogujie.tt.utils.HttpUtilsApache;
import com.mogujie.tt.utils.JsonUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2015/10/19.
 */
public class ChgpwdFragment extends TTBaseFragment {

    private View curView = null;
    private EditText newpassword1,newpassword2,oldpassword;
    private Button DeterminetionOfSubmisson;
    private String newmima;
    private String retypemima;
    private String oldmima;

    private IMServiceConnector imServiceConnector = new IMServiceConnector(){
        @Override
        public void onIMServiceConnected() {
            logger.d("config#onIMServiceConnected");
            IMService imService = imServiceConnector.getIMService();
            if (imService != null) {
                initOptions();
            }
        }

        @Override
        public void onServiceDisconnected() {
        }
    };

    private void initOptions() {



    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle) {
        imServiceConnector.connect(this.getActivity());
        if (null != curView) {
            ((ViewGroup) curView.getParent()).removeView(curView);
            return curView;
        }
        curView = inflater.inflate(R.layout.tt_fragment_chgpwd, topContentView);
        initRes();
        return curView;
    }
    private void initRes() {
        // 设置标题栏
        setTopTitle(getActivity().getString(R.string.changepwd_page_name));
        setTopLeftButton(R.drawable.tt_top_back);
        topLeftContainerLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getActivity().finish();
            }
        });
        setTopLeftText(getResources().getString(R.string.top_left_back));
        initView();
    }

    private void initView() {

        newpassword1 = (EditText) curView.findViewById(R.id.newpwd1);
        newpassword2 = (EditText) curView.findViewById(R.id.newpwd2);
        oldpassword = (EditText) curView.findViewById(R.id.oldpwd);
        inputOperation(newpassword1, curView.findViewById(R.id.new_password_line));
        inputOperation(newpassword2, curView.findViewById(R.id.confirm_password_line));
        inputOperation(oldpassword, curView.findViewById(R.id.old_password_line));


        DeterminetionOfSubmisson = (Button) curView.findViewById(R.id.deter);
        curView.findViewById(R.id.deter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptXgmm();

            }
        });

    }

    private void attemptXgmm() {
        newmima = newpassword1.getText().toString();
        retypemima = newpassword2.getText().toString();
        oldmima = oldpassword.getText().toString();
       if(newmima.equals("")||retypemima.equals("")||oldmima.equals("")){
           Toast.makeText(ChgpwdFragment.this.getActivity(),"输入不能为空！！！",Toast.LENGTH_SHORT).show();
       }else{
           if(newmima.equals(retypemima)){
               dialogview();
           }else {
               Toast.makeText(ChgpwdFragment.this.getActivity(),"密码不一致！！！",Toast.LENGTH_SHORT).show();
           }
       }

    }

    private void dialogview() {
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
        LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View dialog_view = inflater.inflate(R.layout.tt_custom_dialog, null);
        final EditText editText = (EditText)dialog_view.findViewById(R.id.dialog_edit_content);
        editText.setVisibility(View.GONE);
        TextView textText = (TextView)dialog_view.findViewById(R.id.dialog_title);
        textText.setText(R.string.pwdxg_cache_tip);
        builder.setView(dialog_view);

        builder.setPositiveButton(getString(R.string.tt_ok), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
               new ModifyLoginPasswordTask(ChgpwdFragment.this.getActivity()).execute();
            }
        });

        builder.setNegativeButton(getString(R.string.tt_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

    @Override
    protected void initHandler() {
    }

    /**
     * 输入焦点是否失去
     * @param mEditText
     * @param v
     */
    private void inputOperation(EditText mEditText,final View v){
        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                // TODO Auto-generated method stub
                //如果失去焦点
                if (arg1 == false) {
                    v.setBackgroundColor(Color.rgb(211, 211, 211));//灰色
                }
                //如果获得焦点
                else {
                    v.setBackgroundColor(Color.rgb(3,192,43));//青色
                }
            }
        });
    }

    private class  ModifyLoginPasswordTask  extends AsyncTask<Void,Void,String> {

        Context context;
        JSONObject request;
        JSONObject rtjson;//json对象
        String newMessageInfo = "";
        public ModifyLoginPasswordTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                Map<String, Object> parms = new HashMap<String ,Object>();
                parms.put("id", IMLoginManager.instance().getLoginId());
                parms.put("newPassword", newmima);
                parms.put("oldPassword",oldmima);

                request = new JSONObject();//新建json格式
                request = JsonUtil.jsonRequest(RegisterConstant.SERVER_NAME, RegisterConstant.MODIFYLOGINPASSWORD, parms);
                String jsonstr = HttpUtilsApache.usHttpPostJson(RegisterConstant.SERVER_PATH, request);
                JsonUtil jsonUtil=new JsonUtil();//建立json验证
                if(jsonstr.length()>3){
                    rtjson=jsonUtil.getOutputJson(jsonstr);
                    Log.v("", "rtjson = " + rtjson);
                }else{
                    newMessageInfo=HttpUtilsApache.errorMsg(jsonstr);//打印出错信息
                }
            }catch (Exception e){
                e.printStackTrace();

            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if("".equals(newMessageInfo) || newMessageInfo==null)
            {
                if(rtjson!=null && !"".equals(rtjson)){

                    try {
                        String responseCode=rtjson.getString("response_code").toString();
                        if("1".equals(responseCode)) {
                          Toast.makeText(context,"修改密码成功！！！",Toast.LENGTH_LONG).show();
                        }else if("-1".equals(responseCode)) {
                            Toast.makeText(context, rtjson.getString("response_desc").toString(), Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {}
                }
            }
            else {
                Toast.makeText(context, newMessageInfo, Toast.LENGTH_SHORT).show();
            }
        }
    }

}
